package main

import (
	"log"

	"github.com/hyperledger/fabric-sdk-go/pkg/client/ledger"
	"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"

	//gatewayApi "github.com/hyperledger/fabric-sdk-go/pkg/gateway"
	"observ-fabric/channel"
)

const (
	channelID = "chl-01"
	//channelID   = "chl-11"
	chaincodeID = "econtract"
	orgID       = "Org1"
	userID      = "Admin"
	peerUrl     = "grpcs://peer0.org1.example.com:7051"
)

func main() {
	configOpt := config.FromFile("./config/sdk-config.yaml")
	sdk, err := fabsdk.New(configOpt)
	if err != nil {
		log.Fatalf("-X-> 创建新的SDK失败: %v\n", err)
		return
	}
	defer sdk.Close()
	log.Printf("---> 创建SDK成功\n")

	var options_user fabsdk.ContextOption
	var options_org fabsdk.ContextOption

	options_user = fabsdk.WithUser(userID)
	options_org = fabsdk.WithOrg(orgID)

	arChl := channel.GetChannels(sdk, userID, orgID, peerUrl)
	for _, chl := range arChl {
		channel_id := chl
		channelContext := sdk.ChannelContext(channel_id, options_user, options_org)
		client, err := ledger.New(channelContext)
		if err != nil {
			log.Fatalf("-X-> 创建sdk客户端失败: %v\n", err)
			return
		}
		var csi *channel.F_CHL_Summary_Info

		csi, err = channel.GetSummaryInfo(channelContext)
		if err != nil {
			log.Fatalf("-X-> 通道概要信息失败: %v\n", err)
			return
		}
		log.Printf("---> 通道概要信息:\n%+v", csi)
		// ----------------- 区块信息 ----------------
		blk, err := channel.GetBlockInfo(client, uint64(csi.BlockHeight-1))
		if err != nil {
			log.Fatalf("-X-> 区块信息失败: %v\n", err)
			return
		}
		log.Printf("---> 区块信息:\n%+v", blk)
		//blk, err = channel.GetBlockInfo(client, uint64(csi.BlockHeight-2))
		//if err != nil {
		//log.Fatalf("-X-> 区块信息失败: %v\n", err)
		//return
		//}
		//blk, err = channel.GetBlockInfo(client, uint64(csi.BlockHeight-3))
		//if err != nil {
		//log.Fatalf("-X-> 区块信息失败: %v\n", err)
		//return
		//}
	}

	//r3 := channel.GetChannels(sdk, userID, orgID, peerUrl)
	//fmt.Println(r3)

	//gatewayApi.WithConfig()
	//network, err := gatewayApi.GetNetwork("mychannel")
	//orgAdmin := userID
	//ordererOrgName := "Org1"
	//clientContext := sdk.Context(fabsdk.WithUser(orgAdmin), fabsdk.WithOrg(ordererOrgName))
	//fmt.Printf("---> clientContext:\n%v\n", clientContext)

	//resMgmtClient, err := resmgmt.New(clientContext)
	//if err != nil {
	//panic(err)
	//}
	//log.Printf("---> 资源管理客户端信息:\n%+v", resMgmtClient)

	//_, err = resMgmtClient.QueryChannels()
	//if err != nil {
	//panic(err)
	//}
}
